from datetime import datetime
from app import db
from app.utils.time_helper import safe_date_format, safe_datetime_format, safe_time_format


class Order(db.Model):
    """订单模型"""
    __tablename__ = 'orders'
    
    id = db.Column(db.Integer, primary_key=True)
    order_no = db.Column(db.String(32), unique=True, nullable=False, comment='订单号')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    venue_id = db.Column(db.Integer, db.ForeignKey('venues.id'), nullable=False, comment='场馆ID')
    activity_id = db.Column(db.Integer, db.ForeignKey('activities.id'), nullable=True, comment='关联活动ID')
    time_slot_id = db.Column(db.Integer, db.ForeignKey('venue_time_slots.id'), nullable=False, comment='时间段ID')
    
    # 预约信息
    reservation_date = db.Column(db.Date, nullable=False, comment='预约日期')
    start_time = db.Column(db.String(8), nullable=False, comment='开始时间')
    end_time = db.Column(db.String(8), nullable=False, comment='结束时间')
    
        # 金额和状态
    amount = db.Column(db.Numeric(10, 2), nullable=False, comment='订单金额')
    participant_count = db.Column(db.Integer, default=1, comment='预约参与人数')
    actual_attendance = db.Column(db.Integer, default=0, comment='实际到场人数')
    checkin_status = db.Column(db.SmallInteger, default=0, comment='签到状态：0-未签到，1-已签到，2-迟到，3-缺席')
    status = db.Column(db.Integer, default=0, comment='订单状态：0-未支付,1-已支付,2-已取消,3-已完成,4-已退款')
   
    # 附加信息
    remark = db.Column(db.Text, comment='备注')
    checkin_code = db.Column(db.String(6), comment='签到码')
    checkin_time = db.Column(db.DateTime, comment='签到时间')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关系定义
    user = db.relationship('User', back_populates='orders', lazy=True)
    venue = db.relationship('Venue', back_populates='orders', lazy=True)
    activity = db.relationship('Activity', backref='orders', lazy=True)
    time_slot = db.relationship('VenueTimeSlot', backref='orders', lazy=True)
    
    def __repr__(self):
        return f'<Order {self.order_no}>'
    
    def _format_time_field(self, time_value):
        """安全格式化时间字段，处理timedelta对象"""
        if time_value is None:
            return None
        
        # 如果是timedelta对象，转换为时间字符串
        if hasattr(time_value, 'total_seconds'):
            total_seconds = int(time_value.total_seconds())
            hours = total_seconds // 3600
            minutes = (total_seconds % 3600) // 60
            return f"{hours:02d}:{minutes:02d}"
        
        # 如果已经是字符串，直接返回
        if isinstance(time_value, str):
            return time_value
        
        # 如果是其他类型，尝试转换为字符串
        return str(time_value)
    
    def to_dict(self, with_venue=False, with_user=False, with_activity=False):
        """转换为字典格式"""
        
        data = {
            'id': self.id,
            'order_no': self.order_no,
            'user_id': self.user_id,
            'venue_id': self.venue_id,
            'activity_id': self.activity_id,
            'time_slot_id': self.time_slot_id,
            'reservation_date': safe_date_format(self.reservation_date),
            'start_time': self._format_time_field(self.start_time),
            'end_time': self._format_time_field(self.end_time),
            'amount': float(self.amount) if self.amount else 0,
            'participant_count': self.participant_count or 1,
            'actual_attendance': self.actual_attendance or 0,
            'status': self.status,
            'status_text': self.get_status_text(),
            'remark': self.remark,
            'checkin_code': self.checkin_code,
            'checkin_time': safe_datetime_format(self.checkin_time),
            'created_at': safe_datetime_format(self.created_at),
            'updated_at': safe_datetime_format(self.updated_at)
        }
        
        # 包含场馆信息
        if with_venue and self.venue:
            data['venue'] = self.venue.to_dict()
            
        # 包含时间段信息
        if self.time_slot:
            data['time_slot'] = {
                'id': self.time_slot.id,
                'day_of_week': self.time_slot.day_of_week,
                'start_time': self.time_slot.start_time,  # VenueTimeSlot.start_time 已经是字符串
                'end_time': self.time_slot.end_time,      # VenueTimeSlot.end_time 已经是字符串
                'price': float(self.time_slot.price) if self.time_slot.price else 0,
                'capacity': self.time_slot.capacity
            }
        
        # 包含用户信息
        if with_user and self.user:
            data['user'] = {
                'id': self.user.id,
                'name': self.user.nickname or f'用户{self.user.id}',
                'nickname': self.user.nickname,
                'phone': self.user.phone or '',
                'avatar_url': self.user.avatar_url
            }
        
        # 包含活动信息
        if with_activity and self.activity:
            data['activity'] = {
                'id': self.activity.id,
                'title': self.activity.title,
                'description': self.activity.description,
                'activity_type': self.activity.activity_type,
                'start_time': safe_datetime_format(self.activity.start_time),
                'end_time': safe_datetime_format(self.activity.end_time),
                'fee': float(self.activity.fee) if self.activity.fee else 0,
                'is_free': self.activity.is_free,
                'status': self.activity.status
            }
        elif self.activity:
            # 至少包含活动标题
            data['activity_title'] = self.activity.title
        else:
            data['activity_title'] = '无关联活动'
            
        return data
    
    def get_status_text(self):
        """获取状态文本"""
        status_map = {
            0: '未支付',
            1: '已支付',
            2: '已取消',
            3: '已完成',
            4: '已退款'
        }
        return status_map.get(self.status, '未知状态')
    
    def can_cancel(self):
        """判断是否可以取消"""
        from datetime import date
        # 只有未支付或已支付的订单可以取消，且预约日期未过期
        if self.status in [0, 1] and self.reservation_date >= date.today():
            return True
        return False
    
    def can_checkin(self):
        """判断是否可以签到"""
        from datetime import date
        # 只有已支付的订单在预约当天可以签到
        if self.status == 1 and self.reservation_date == date.today():
            return True
        return False 